import {
  Body,
  Controller,
  Get,
  Inject,
  ParseIntPipe,
  Post,
  Param,
  Put,
  Delete,
} from '@nestjs/common';
import { ScenicControlService } from './ScenicControl.service';
import {
  CheckAdmin,
  RequireLogin,
  UserInfo,
} from '@/decorator/index.decorator';
import ScenicListDto from '@/dto/ScenicList.dto';
import CreateScenicDto from '@/dto/CreateScenic.dto';
import UpadateScenicDto from '@/dto/UpadateScenic.dto';

@Controller('admin/scenic')
export class ScenicControlController {
  @Inject(ScenicControlService)
  private readonly scenicControlService: ScenicControlService;

  fommatRes(item) {
    item.scenic_img = item.scenic_img.map((i: any) => i.img);
    // eslint-disable-next-line
    const { createdAt, updatedAt, ...rest } = item;
    return rest;
  }

  @Post('list')
  async getScenicList(@Body() data: ScenicListDto) {
    const { pageNum, pageSize, spot, region, type, sort } = data;

    const res = await this.scenicControlService.getScenicList(
      pageNum,
      pageSize,
      spot,
      region,
      type,
      sort,
    );

    res.list = res.list.map((item: any) => this.fommatRes(item));
    return res;
  }

  @Get('/:id')
  @RequireLogin()
  async getScenicDetail(
    @UserInfo() userInfo,
    @Param('id', ParseIntPipe) id: number,
  ) {
    const res = await this.scenicControlService.getScenicDetail(id);
    if (userInfo.phone) {
      const isCollect = await this.scenicControlService.getCollectInfo(
        userInfo.userId,
        id,
      );
      return {
        ...this.fommatRes(res),
        isCollect,
      };
    }
    return this.fommatRes(res);
  }

  @Post()
  @CheckAdmin()
  async createScenic(@Body() body: CreateScenicDto) {
    const data = await this.scenicControlService.getFillInfo(body);

    const res = await this.scenicControlService.createScenic(data);
    return '添加' + (res && '成功') || '失败';
  }

  @Put()
  @CheckAdmin()
  async updateScenic(@Body() body: UpadateScenicDto) {
    let data = body;

    const scenic = await this.scenicControlService.getScenicDetail(body.id);
    if (scenic.addr !== body.addr) {
      data = await this.scenicControlService.getFillInfo(body);
    }

    const res = await this.scenicControlService.updateScenic(data);
    return '修改' + (res && '成功') || '失败';
  }

  @Delete('/:id')
  @CheckAdmin()
  async deleteScenic(@Param('id', ParseIntPipe) id: number) {
    const res = await this.scenicControlService.deleteScenic(id);
    return '删除' + (res && '成功') || '失败';
  }
}
